import os
import platform
from pathlib import Path


def check_result_dir():
    my_dir = os.path.dirname(__file__)
    workdir_name = 'result'
    workdir = my_dir + os.sep + workdir_name
    os.chdir(my_dir)
    if not Path(workdir).is_dir():
        os.mkdir(workdir_name)


def save_result(myfile_name_: str, data):
    myfile_name = 'result' + os.sep + myfile_name_
    with open(myfile_name, 'w+', encoding="utf-8") as file:
        for item in data:
            file.write(item)
            # file.write('hello')

    print(myfile_name + '写入完成')


def schedule_process(wfilename, data):
    check_result_dir()
    save_result(wfilename, data)
    merge()


def merge():
    workdir_name = 'result'
    my_dir = os.path.dirname(__file__)
    workdir = my_dir + os.sep + workdir_name
    filenames = os.listdir(workdir)
    # print(filenames)
    if platform.system() == 'Linux':
        output = '/var/www/html/' + 'allinone.m3u'
    else:
        output = my_dir + os.sep + 'allinone.m3u'
    # print(output)
    with open(output, 'w+', encoding='utf-8') as file:
        for filename in filenames:
            filepath = workdir + os.sep + filename
            with open(filepath, 'r', encoding='utf-8') as file_line:
                for line in file_line.readlines():
                    # print(line)
                    file.writelines(line)
    print('文件合并完毕')
